//
//  TMUserManager.m
//  国学商家管理
//
//  Created by mac on 2018/6/19.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMUserManager.h"
#import "TMUserModel.h"
@implementation TMUserManager
+(TMUserManager *)deaufatManager
{
    static TMUserManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc]init];
//        [[NSNotificationCenter defaultCenter]addObserver:manager selector:@selector(connectionChanged) name:WZConnectionChanged object:nil];
    });
    return manager;
}
- (TMUserModel *)userModel{
    if (_userModel) {
        return _userModel;
    }
    //0a3b6f64f0523984e51323fe53b8c504
    if (_userModel==nil) {
        NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:@"kUSER_INFOR_KEY"];
        if (userData && userData.length != 0) {
            _userModel = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
            
        }
        return _userModel;
        
    }
    return nil;
}
+ (BOOL)hasLogin {
    return [TMUserManager deaufatManager].hasLogin;
}

- (BOOL)hasLogin {
    if (_userModel.uid) {
        return YES;
    }
    return NO;
}
+ (void)autoLogin {
//    switch ([TMUserManager deaufatManager].userModel.loginType) {
//        case LoginTypePhone:
//        {
//            
//        }
//            break;
//        case LoginTypeUserName:
//        {}
//            break;
//        case LoginTypeWechat:
//        {}
//            break;
//        default:
//            break;
//    }
}
+ (void)logoutSuccessed:(successBlock)success{
    NSDictionary *dic = @{@"uid":@([TMUserManager deaufatManager].userModel.uid),@"token":[TMUserManager deaufatManager].userModel.token};
    [[TMDataRequest defaultRequest] requestWithPath:TMAPI_Logout parameters:dic method:TMDataRequestTypeGet prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
//       [TMProgressHUD showSuccessWithStyleDarkStatus:responseObject[@"msg"]];
        //清除本地数据/
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showErrorWithStyleDarkStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [TMProgressHUD showErrorWithStyleDarkStatus:@"网络错误！"];
    }];
}
+ (void)loginWithUserName:(NSString *)userName password:(NSString *)password successed:(successBlock)success{
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"registrationID"];
    if (str == nil) {
        str = @"123";
    }
    NSDictionary *dic = @{@"phone":userName,@"password":password,@"type":@"password_login",@"device":str};
    [[TMDataRequest defaultRequest] requestWithPath:TMAPI_UserNameLogin parameters:dic method:TMDataRequestTypePost prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        //d2cd33e9c0236a8c2d8bd3fa91ad3acf
        NSLog(@"%@", responseObject);
        TMUserModel *user = [TMUserModel yy_modelWithDictionary:responseObject];
        user.userName = userName;
        user.password = password;
        user.loginType = LoginTypeUserName;
        [[TMUserManager deaufatManager] updateUserModel:user];
        //[TMUserManager pathForCacheObj:user ToLoaclPath:PATH_USER];
        //05c7ac946880ad7eed28166b478c7277
        if (success) {
            success(responseObject);
        }
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showErrorWithStyleDarkStatus:errorMessage];
//        if ([errorMessage isEqualToString:<#(nonnull NSString *)#>]) {
//            <#statements#>
//        }
//        [[TMUserManager deaufatManager] updateUserModel:nil];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [TMProgressHUD showErrorWithStyleDarkStatus:@"网络错误！"];
    }];
}
+ (void)loginWithPhone:(NSString *)userName code:(NSString *)password successed:(successBlock)success{
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"registrationID"];
    //            NSDictionary *dic = @{@"phone":userName,@"password":password,@"type":@"password_login",@"device":str};
    NSDictionary *dic = @{@"phone":userName,@"verify":password,@"type":@"phone",@"device":str};
    [[TMDataRequest defaultRequest] requestWithPath:TMAPI_UserNameLogin parameters:dic method:TMDataRequestTypePost prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        if (success) {
            success(responseObject);
        }
        NSLog(@"%@", responseObject);
        TMUserModel *user = [TMUserModel yy_modelWithDictionary:responseObject];
        user.userName = userName;
        user.password = password;
        user.loginType = LoginTypePhone;
        [[TMUserManager deaufatManager] updateUserModel:user];
        //[TMUserManager pathForCacheObj:user ToLoaclPath:PATH_USER];
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showErrorWithStyleDarkStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [TMProgressHUD showErrorWithStyleDarkStatus:@"网络错误！"];
    }];
}
+ (void)findPasswordWithDictionary:(NSDictionary *)dic Success:(successBlock)block{
    [[TMDataRequest defaultRequest] requestWithPath:TMAPI_FindPsw parameters:dic method:TMDataRequestTypePost prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        block(responseObject);
        [TMProgressHUD showSuccessWithStatus:responseObject[@"msg"]];
//        [self loginWithUserName:dic[@"phone"] password:dic[@"password"] successed:block];
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showErrorWithStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [TMProgressHUD showErrorWithStyleDarkStatus:@"网络错误！"];
    }];
}
+ (void)changePasswordWithDictionary:(NSDictionary *)dic Success:(successBlock)block{
    [[TMDataRequest defaultRequest] requestWithPath:TMAPI_changePsw parameters:dic method:TMDataRequestTypePost prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        block(responseObject);
        [TMProgressHUD showSuccessWithStatus:responseObject[@"msg"]];
       // [self loginWithUserName:dic[@"phone"] password:dic[@"password"] successed:block];
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showErrorWithStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [TMProgressHUD showErrorWithStatus:@"请求失败！"];
    }];
}




+ (void)registerWithDictionary:(NSDictionary *)dic Success:(successBlock)block{
    [[TMDataRequest defaultRequest] requestWithPath:TMAPI_UserRegister parameters:dic method:TMDataRequestTypePost prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        block(responseObject);
        [TMProgressHUD showSuccessWithStyleDarkStatus:@"注册成功"];
        //[self loginWithUserName:dic[@"phone"] password:dic[@"password"] successed:block];
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showErrorWithStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [TMProgressHUD showErrorWithStyleDarkStatus:@"网络错误！"];
    }];
}
+ (void)verificationCodeSendWithDictionary:(NSString*)phone{
    NSDictionary *param = @{@"phone":phone};
    [[TMDataRequest defaultRequest] requestWithPath:TMAPI_VerificationCodeSend parameters:param method:TMDataRequestTypePost prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
        [TMProgressHUD showSuccessWithStyleDarkStatus:responseObject[@"msg"]];
        
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showSuccessWithStyleDarkStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [TMProgressHUD showErrorWithStyleDarkStatus:@"网络错误！"];
    }];
}


- (void)updateUserModel:(TMUserModel *)user {
    self.userModel = user;
    [TMUserManager displayRCConfings];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"kUSER_INFOR_KEY"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
//上传图片
+ (void)changeUserIcon:(UIImage *)image Success:(successBlock)block{
    //上传图片
    NSDictionary* params= @{@"uid":@([TMUserManager deaufatManager].userModel.uid),@"token":[TMUserManager deaufatManager].userModel.token};
        //上传图片 ,@"file":icon
    if (image == nil) {
        return;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",nil];//,@"application/json"
        [manager POST:@"http://app.yxp123.com/index.php/home/base/pic" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSData *eachImgData = UIImageJPEGRepresentation(image, 0.1);
            //NSLog(@"ddddd%@", eachImgData);
            [formData appendPartWithFileData:eachImgData name:[NSString stringWithFormat:@"file"] fileName:[NSString stringWithFormat:@"file.png"] mimeType:@"image/jpeg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"%@", responseObject);
           block(responseObject[@"pic"]);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"error%@", error);

        }];
}
+(void)uploadImageAndMovieBaseModel:(NSString *)paths Success:(successBlock)block{
    
    //获取文件的后缀名
    NSString *extension = [paths componentsSeparatedByString:@"."].lastObject;
    
    //设置mimeType
    NSString *mimeType = [NSString stringWithFormat:@"video/%@", extension];
    NSDictionary* params= @{@"uid":@([TMUserManager deaufatManager].userModel.uid),@"token":[TMUserManager deaufatManager].userModel.token};
    //创建AFHTTPSessionManager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //设置响应文件类型为JSON类型
    manager.responseSerializer    = [AFJSONResponseSerializer serializer];
    
    //初始化requestSerializer
    manager.requestSerializer     = [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = nil;
    
    //设置timeout
    [manager.requestSerializer setTimeoutInterval:20.0];
    
    //设置请求头类型
    [manager.requestSerializer setValue:@"form/data" forHTTPHeaderField:@"Content-Type"];
    
    //设置请求头, 授权码
    //[manager.requestSerializer setValue:@"YgAhCMxEehT4N/DmhKkA/M0npN3KO0X8PMrNl17+hogw944GDGpzvypteMemdWb9nlzz7mk1jBa/0fpOtxeZUA==" forHTTPHeaderField:@"Authentication"];
    
    //上传服务器接口
    NSString *url = [NSString stringWithFormat:@"http://app.yxp123.com/index.php/api/index/pic"];
    
    //开始上传
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSError *error;
        BOOL success1 = [formData appendPartWithFileURL:[NSURL fileURLWithPath:paths] name:@"file" fileName:[NSString stringWithFormat:@"file.mp4"] mimeType:mimeType error:&error];
        if (!success1) {
            
            NSLog(@"appendPartWithFileURL error: %@", error);
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        [TMProgressHUD showProgress:uploadProgress.fractionCompleted status:@"上传中..."];
        NSLog(@"上传进度: %f", uploadProgress.fractionCompleted);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [TMProgressHUD dismiss];
        block(responseObject[@"pic"]);
        NSLog(@"成功返回: %@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败: %@", error);
    }];
}

+ (void)loginWithWecatWith:(NSDictionary *)dic Successed:(successBlock)success{
    [[TMDataRequest defaultRequest]requestWithPath:TMAPI_LoginWithWechat parameters:dic method:1 prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        TMUserModel *user = [TMUserModel yy_modelWithDictionary:responseObject];
        user.userName = dic[@"nickname"];
        user.loginType = LoginTypeWechat;
        user.userIcon = dic[@"headimgurl"];
        user.userOpenid = dic[@"openid"];
        //user.password = dic;
        [[TMUserManager deaufatManager] updateUserModel:user];
       // [TMUserManager pathForCacheObj:user ToLoaclPath:PATH_USER];
        success(responseObject);
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showErrorWithStyleDarkStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

+(NSMutableDictionary *)paramDisplay{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if ([TMUserManager deaufatManager].userModel.token != nil) {
        [param setValue:@([TMUserManager deaufatManager].userModel.uid) forKey:@"uid"];
        [param setValue:[TMUserManager deaufatManager].userModel.token forKey:@"token"];
    }
    return param;
}

+ (void)displayRCConfings{
//        [[RCIM sharedRCIM] initWithAppKey:IMClodeAppKey];
       // [[RCIM sharedRCIM] disconnect:YES];
        [[RCIM sharedRCIM] connectWithToken:[TMUserManager deaufatManager].userModel.rongyun success:^(NSString *userId) {
            NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
        } error:^(RCConnectErrorCode status) {
            NSLog(@"登陆的错误码为:%ld", (long)status);
        } tokenIncorrect:^{
            //token过期或者不正确。
            //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
            //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
            [TMProgressHUD showInfoWithStyleDarkStatus:@"token错误，请重新登录"];
            NSLog(@"token错误");
        }];
}

+ (void)blindPhoneWith:(NSDictionary *)dic Successed:(successBlock)success{
    [[TMDataRequest defaultRequest]requestWithPath:TMAPI_blindPhone parameters:dic method:1 prepareExecute:^{
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        TMUserModel *user = [TMUserModel yy_modelWithDictionary:responseObject];
        user.userName = dic[@"nickname"];
        user.loginType = LoginTypeWechat;
        user.userIcon = dic[@"headimgurl"];
        user.userOpenid = dic[@"openid"];
        //user.password = dic;
        [[TMUserManager deaufatManager] updateUserModel:user];
        //[TMUserManager pathForCacheObj:user ToLoaclPath:PATH_USER];
        success(responseObject);
    } error:^(NSInteger errorCode, NSString *errorMessage) {
        [TMProgressHUD showErrorWithStyleDarkStatus:errorMessage];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

+ (NSString *) pathForCacheObj:(id)obj ToLoaclPath:(NSString *) path {
    NSString *document = [self pathWithControllerName:path];
    if (document.length==0) {
        return @"";
    }
    [TMUserManager displayRCConfings];
    NSMutableData * mutDate = [[NSMutableData alloc] init];
    NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mutDate];
    [archiver encodeObject:obj forKey:path];
    [archiver finishEncoding];
    [mutDate writeToFile:document atomically:YES];
    
    return document;
}

+ (id) objFromPath:(NSString *) path{
    NSString * document = [self pathWithControllerName:path];
    NSMutableData * data = [[NSMutableData alloc] initWithContentsOfFile:document];
    NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    //NSLog(@"path %@",document);
    id obj = [unarchiver decodeObjectForKey:path];
    [unarchiver finishDecoding];
    return obj;
}
+ (NSString *) pathWithControllerName:(NSString*) name{
    
    NSString * cache =  [NSHomeDirectory() stringByAppendingString:@"/Documents/Caches"];
    
    NSString * fullPath = [cache stringByAppendingFormat:@"/%@.plist",name];
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:cache]) {
        if (![manager createDirectoryAtPath:cache withIntermediateDirectories:YES attributes:nil error:nil]) {
            NSLog(@"创建文件夹路径失败");
            return @"";
        }
    }
    //NSLog(@"%@",fullPath);
    return fullPath;
}
@end
